package com.three;

import android.text.TextUtils;

import com.fast.dev.frame.utils.Base64;
import com.fast.dev.frame.utils.LogUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 说明：优酷工具类
 * <p/>
 * 作者：fanly
 * <p/>
 * 时间：2016/3/8 9:56
 * <p/>
 * 版本：verson 1.0
 */
public final class YouKuUtils {

    private final static String URL = "http://play.youku.com/play/get.json?vid=%s&ct=12";

    private YouKuUtils() {
    }

    /**
     * 说明：解析优酷真实地址
     *
     * @param json
     * @return
     */
    public static String getYouKuUrl(String link, String json) {
        String youkuUrl = "";
        String vid, ep,token,sid,type="";
        long oip;
        if (TextUtils.isEmpty(json)) {
            return youkuUrl;
        }
        try {
            vid = getVid(link);

            JSONObject jsonObject = new JSONObject(json);

            JSONObject data = jsonObject.getJSONObject("data");

            JSONArray stream = data.getJSONArray("stream");

            if (stream.length() > 0){
                JSONObject object = stream.getJSONObject(stream.length()-1);
                String streamType = object.optString("stream_type");
                type = streamType;
//                if (streamType.startsWith("mp4hd")){
//                    type = "mp4";
//                }else if (streamType.startsWith("flvhd")){
//                    type = "flvhd";
//                }else if (streamType.startsWith("3gp")){
//                    type = "3gphd";
//                }else {
//                    type = "3gphd";
//                }
            }

            JSONObject security = data.getJSONObject("security");

            oip = security.getLong("ip");
            ep = security.getString("encrypt_string");
            String [] result = getEpTokenSid(vid,ep);
            ep = URLEncoder.encode(result[0],"UTF-8");
            token = result[1];
            sid = result[2];

            youkuUrl = getYouKuRealUrl(ep,oip,sid,token,type,vid);
        } catch (Exception e) {
            LogUtils.e(e);
        }
        return youkuUrl;
    }

    /**
     * 说明：获取Json
     *
     * @param link
     * @return
     */
    public static String getJson(String link) {
        if (TextUtils.isEmpty(link)) {
            return "";
        }
        return String.format(URL, getVid(link));
    }

    /**
     * 说明：获取视频的ID
     *
     * @param link
     * @return
     */
    private static String getVid(String link) {
        return link.substring(link.lastIndexOf('/') + 4, link.length() - 5);
    }

    /**
     * 说明：ep,token,sid
     * @param vid
     * @param ep
     * @return
     */
    public static String[] getEpTokenSid(String vid, String ep) {
        String[] result = new String[3];
        String template1 = "becaf9be";
        String template2 = "bf7e5f01";
        byte[] bytes = Base64.decode(ep);
        ep = new String(bytes);
        String temp = myEncoder(template1, bytes, false);
        String[] part = temp.split("_");
        String sid = part[0];
        String token = part[1];
        String whole = String.format("%s_%s_%s", sid, vid, token);
        byte[] newbytes = whole.getBytes();
        result[0] = myEncoder(template2, newbytes, true);
        result[1] = token;
        result[2] = sid;
        return result;
    }

    private static String myEncoder(String a, byte[] c, boolean isToBase64) {
        String result = "";
        List<Byte> bytesR = new ArrayList<>();
        int f = 0, h = 0, q = 0;
        int[] b = new int[256];
        for (int i = 0; i < 256; i++)
            b[i] = i;
        while (h < 256) {
            f = ((f + b[h] + a.charAt(h % a.length())) % 256);
            int temp = b[h];
            b[h] = b[f];
            b[f] = temp;
            h++;
        }
        f = 0;
        h = 0;
        q = 0;
        while (q < c.length) {
            h = (h + 1) % 256;
            f = (f + b[h]) % 256;
            int temp = b[h];
            b[h] = b[f];
            b[f] = temp;
            byte[] bytes = new byte[]{(byte) (c[q] ^ b[(b[h] + b[f]) % 256])};
            bytesR.add(bytes[0]);
            result += new String(bytes);
            q++;
        }
        if (isToBase64) {
            Byte[] byteR = bytesR.toArray(new Byte[bytesR.size()]);
            byte[] temp = new byte[byteR.length];
            for (int i = 0; i < byteR.length; i++) {
                temp[i] = byteR[i];
            }
            result = Base64.encode(temp);
        }
        return result;
    }


    /**
     * 说明：拼接url
     *
     * @param ep
     * @param oip
     * @param sid
     * @param token
     * @param type
     * @param vid
     * @return
     */
    private static String getYouKuRealUrl(String ep, long oip, String sid, String token, String type, String vid) {
        return "http://pl.youku.com/playlist/m3u8?ctype=12&ep=" + ep + "&ev=1&keyframe=1&oip=" + oip +
                "&sid=" + sid + "&token=" + token +
                "&type=" + type + "&vid=" + vid;
    }
}
